package com.cloudfun.campusshare.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author : linyangping
 * @Date : Created in 10:24 PM 2019/11/19
 */
@Slf4j
@Component
public class AliyunOSSUtil implements InitializingBean {

    @Value("${aliyun.endpoint}")
    private String endpoint;

    @Value("${aliyun.accessKey}")
    private String accessKey;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret = "F2JMDKSDVaQPpyVd64blRv3s9vwanc";

    @Value("${aliyun.oss.bucketName}")
    private String BUCKET_NAME;

    private OSSClient ossClient;

    /**
     * 获取默认bucket
     *
     * @return
     */
    public String getDefaultBucketName() {
        return BUCKET_NAME;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ossClient = new OSSClient(endpoint, accessKey, accessKeySecret);
        if (!ossClient.doesBucketExist(BUCKET_NAME)) {
            throw new RuntimeException("阿里云OSS异常，bucket不存在：" + BUCKET_NAME);
        }
    }


    /**
     * 保存文件
     *
     * @param multipartFile
     * @param objectName
     */
    public void saveFile(MultipartFile multipartFile, String objectName) {
        this.saveFile(multipartFile, BUCKET_NAME, objectName);
    }

    /**
     * 保存文件
     *
     * @param multipartFile
     * @param bucketName
     * @param objectName
     */
    public void saveFile(MultipartFile multipartFile, String bucketName, String objectName) {
        if (!ossClient.doesBucketExist(BUCKET_NAME)) {
            throw new RuntimeException("阿里云OSS异常，bucket不存在：" + BUCKET_NAME);
        }
        try (InputStream inputStream = multipartFile.getInputStream()) {
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (IOException e) {
            log.error("阿里云oss文件上传出错：", e);
            throw new BusinessException(Code.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 保存文件
     *
     * @param file
     * @param objectName
     */
    public void saveFile(File file, String objectName) {
        this.saveFile(file, BUCKET_NAME, objectName);
    }

    /**
     * 保存文件
     *
     * @param file
     * @param bucketName
     * @param objectName
     */
    public void saveFile(File file, String bucketName, String objectName) {
        if (!ossClient.doesBucketExist(BUCKET_NAME)) {
            throw new RuntimeException("阿里云OSS异常，bucket不存在：" + BUCKET_NAME);
        }
        try (InputStream inputStream = new FileInputStream(file);) {
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (IOException e) {
            log.error("阿里云oss文件上传出错：", e);
            throw new BusinessException(Code.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 获取文件url
     *
     * @param objectName
     * @return
     */
    public String getFileUrl(String objectName) {
        return this.getFileUrl(BUCKET_NAME, objectName);
    }

    /**
     * 获取文件url
     *
     * @param bucketName
     * @param objectName
     * @return
     */
    public String getFileUrl(String bucketName, String objectName) {
        if (!ossClient.doesBucketExist(BUCKET_NAME)) {
            throw new RuntimeException("阿里云OSS异常，bucket不存在：" + BUCKET_NAME);
        }
        String prefix = objectName.substring(objectName.lastIndexOf("."));
        String url = "http://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + objectName;
        if (prefix.equals(".jpg") || prefix.equals(".JPG") || prefix.equals(".jpeg") || prefix.equals(".png")) {
            url = url + "?x-oss-process=image/auto-orient,1";
        }
        return url;
    }

    /**
     * 删除文件
     *
     * @param objectName
     */
    public void deleteFile(String objectName) {
        this.deleteFile(BUCKET_NAME, objectName);
    }

    /**
     * 删除文件
     *
     * @param bucketName
     * @param objectName
     */
    public void deleteFile(String bucketName, String objectName) {
        if (!ossClient.doesBucketExist(BUCKET_NAME)) {
            throw new RuntimeException("阿里云OSS异常，bucket不存在：" + BUCKET_NAME);
        }
        ossClient.deleteObject(bucketName, objectName);
    }
    /**
     * 获取对象流
     * @param objectName
     * @return
     */
    public InputStream getObject(String objectName){
        return ossClient.getObject(BUCKET_NAME, objectName).getObjectContent();
    }

    /**
     * 获取OSS对象
     *
     * @param bucketName
     * @param objectName
     * @return
     */
    public OSSObject getObject(String bucketName, String objectName) {
        if (!ossClient.doesBucketExist(BUCKET_NAME)) {
            throw new RuntimeException("阿里云OSS异常，bucket不存在：" + BUCKET_NAME);
        }
        return ossClient.getObject(bucketName, objectName);
    }
}
